/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-04-24 20:21:26
 * @LastEditTime: 2025-05-19 19:40:03
 * @FilePath: /monitor_belt/src/views/login/components/form.tsx
 */
/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-04-24 20:21:26
 * @LastEditTime: 2024-04-24 20:59:19
 * @FilePath: /steel_live/src/views/login/components/form.tsx
 */
import { useNavigate } from "react-router-dom";
import { Button, Form, Input, message, Spin } from "antd";
import {
  UserOutlined,
  LockOutlined,
} from "@ant-design/icons";
import styles from "./index.module.scss";
import { useState } from "react";
import { setCache } from "@/utils/storage";
import { rules } from "./rules";
import { login } from "@/api/login";

type ILogin = {
  username: string;
  password: string;
};
const LoginForm = () => {
  let navigate = useNavigate();
  let [code, setCode] = useState<string>("");
  const [loading, setLoading] = useState<boolean>(false);
  const onFinish = async (values: ILogin) => {
    try {
      setLoading(true);
      message.loading("登录中...",0)
      setCache("token", "");
      let res = await login({
        username: values.username,
        password: values.password,
      });
      let { token } = res.data;
      message.destroy();
      message.success("登录成功");
      setCache("token", token);
      navigate("/");
      return Promise.resolve();
    } finally {
      setLoading(false);
      message.destroy();
      return Promise.resolve();
    }
  };
  const onFinishFailed = (_errorInfo: any) => {
    return Promise.reject("请完善信息");
  };
  //验证码切换
  const codeChange = (value: string) => {
    setCode(value);
  };
  return (
    <Spin spinning={loading}>
      <div className={styles.form_wrapper}>
        <h2 className={styles.header}>{import.meta.env.VITE_NAME}</h2>
        <Form
          name="basic"
          style={{ width: "100%" }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item label="" name="username" rules={rules.username}>
            <Input
              addonBefore={<UserOutlined />}
              size="large"
              placeholder="请输入账号"
            />
          </Form.Item>

          <Form.Item label="" name="password" rules={rules.password}>
            <Input.Password
              addonBefore={<LockOutlined />}
              size="large"
              placeholder="请输入密码"
            />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              style={{ width: "100%" ,marginTop:'20px'}}
              size="large"
              htmlType="submit"
            >
              登 录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </Spin>
  );
};

export default LoginForm;
